import time
import os
import autoit

from qturboframe.lib.ranorex.exceptions import CsClientError
from qturboframe.lib.utils.windows.win_control import WinControl
from qturboframe.lib.report.log import logger
from qturboframe.lib.utils.CustomError.custom_error import CustomError
from qturboframe.lib.utils.CustomError.custom_exception import CustomException


def upload_file_for_chrome(file, TIMEOUT=3):
    logger.info("开始文件上传")
    if not os.path.isfile(file):
        logger.debug(file)
        raise CustomException(CustomError.Error_EQ03004000_Not_File_Path,extra_msg="<{0}>尖括号内的文件路径不正确".format(file))
        # raise CsClientError("请输入文件路径")

    wc = WinControl("打开")
    #20秒超时时间确保“打开”框打开
    wc.wait(20)
    wc.activate()
    time.sleep(TIMEOUT)
    try:
        wc.control_focus("Edit1")
    except Exception as e:
        logger.info(str(e))
        pass
    # 选中上传的文件
    logger.debug("选择文件")
    exc_msg = ''
    for i in range(5):
        try:
            wc.control_settext("Edit1", file)
            break
        except Exception as e:
            exc_msg = str(e)
            logger.debug(str(e))
    else:
        raise BaseException(exc_msg)
    time.sleep(TIMEOUT)
    # 点击打开按钮
    logger.debug("点击打开按钮")
    i = 0
    for i in range(3):
        try:
            if wc.exists():
                logger.info("上传文件入口")
                wc.control_focus("Button1")
                wc.control_click("Button1")
                try:
                    logger.info("再次关闭")
                    wc.control_click("Button1")
                    wc.control_click("Button1")
                except Exception as e:
                    pass
            break
        except autoit.AutoItError as e:
            logger.info(file)
            raise CsClientError(str(e))
    else:
        raise Exception("上传文件失败")


def upload_file_for_firfox(file, TIMEOUT=3):

    wc = WinControl("文件上传")
    try:
        wc.control_focus("Edit1")
    except:
        try:
            wc = WinControl("打开")
            try:
                wc.control_focus("Edit1")
            except:
                pass
        except:
            pass
    wc.wait(10)
    wc.activate()
    wc.control_focus("Edit1")
    # 选中上传的文件
    logger.debug("选择文件")
    wc.control_settext("Edit1", file)
    time.sleep(TIMEOUT)
    # 点击打开按钮
    logger.debug("点击打开按钮")
    for i in range(3):
        try:
            if wc.exists():
                wc.control_click("Button1")
            break
        except autoit.AutoItError as e:
            logger.info(str(e))
            pass
    else:
        raise Exception("上传文件失败")


if __name__ == '__main__':
    upload_file_for_firfox("")